"""
@Time : 2022/10/11
@Author : Gloria
"""

from django.contrib import auth
from app01.models import UserInfo, Avatars
from django.views import View
from django.http import JsonResponse
import random
from api.forms.login_form import LoginForm, SignForm



# 登录失败的可复用代码
def clean_form(form):
    err_dict: dict = form.errors
    # 拿到所有错误的字段名字
    err_valid = list(err_dict.keys())[0]
    # 拿到第一个字段的第一个错误信息
    err_msg = err_dict[err_valid][0]
    return err_valid, err_msg


# CBV
class LoginView(View):
    # 登入视图
    def post(self, request):
        res = {
            'code': 425,
            'msg': "登录成功！",
            'self': None
        }
        form = LoginForm(request.data, request=request)
        if not form.is_valid():
            # 验证不通过
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)

        # 写我们的登录操作
        user = form.cleaned_data.get('user')
        # 登录操作
        auth.login(request, user)
        res['code'] = 0
        return JsonResponse(res)

# 注册视图
class SignView(View):
    def post(self, request):
        res = {
            'code': 425,
            'msg': "注册成功！",
            'self': None
        }
        form = SignForm(request.data, request=request)

        if not form.is_valid():
            # 验证不通过
            res['self'], res['msg'] = clean_form(form)
            return JsonResponse(res)

        # 注册成功的代码
        user = UserInfo.objects.create_user(
            username=request.data.get('name'),
            password=request.data.get('pwd'),
        )
        # 随机选择头像
        avatar_list = [i.nid for i in Avatars.objects.all()]
        user.avatar_id = random.choice(avatar_list)

        # user.avatar_url = Avatars.objects.filter(nid=user.avatar_id)

        user.abstract = '请到个人中心完善/编辑个人相关信息'
        user.nick_name = request.data.get('name')
        user.save()

        # 注册之后直接登录
        auth.login(request, user)
        res['code'] = 0

        return JsonResponse(res)


































